﻿using System;
using System.Collections.Generic;
using Enums;
using XF.ExControls;
using XF.Common;
using System.Windows.Forms;

namespace KYBM
{
    public partial class FrmDTODetail : XFFormEx
    {
        private readonly XF.BLL.Bill_DTOHead bll = new XF.BLL.Bill_DTOHead();
        private readonly XF.BLL.Bill_DTOItems bllItems = new XF.BLL.Bill_DTOItems();
        private readonly XF.BLL.Base_Materiel bllMateriel = new XF.BLL.Base_Materiel();
        private readonly XF.BLL.Base_Customer bllCustomer = new XF.BLL.Base_Customer();
        private XF.Model.Bill_DTOHead head;
        private int iCustomerId = -1;

        public FrmDTODetail(int id)
        {
            InitializeComponent();
            //表单头
            head = bll.GetDetailModel(id);
        }

        private void tsBtnSave_Click(object sender, EventArgs e)
        {
            xfDataGridView1.EndEdit();
            string msg = CheckInput();
            if (msg.Equals(string.Empty))
            {
                UpdateOrder();
            }
            else
            {
                QQMessageBox.Show(
                this,
                msg,
                MessageText.MESSAGEBOX_CAPTION_TIP,
                QQMessageBoxIcon.Information,
                QQMessageBoxButtons.OK);
            }
        }

        

        /// <summary>
        /// 保存订单
        /// </summary>
        private void UpdateOrder()
        {
            head.OrderDate = dtpOrderDate.Value.Date;
            head.Remark = tbOrderRemark.Text;
            head.PayType = zDataConverter.ToInt(cmbPayType.SelectedValue);
            head.Status = zDataConverter.ToInt(cmbStatus.SelectedValue);
            head.PayAmount = zDataConverter.ToDecimal(tbPayAmount.Text);
            XF.Model.Base_Customer customer = bllCustomer.GetModel((int)head.CustomerId);
            customer.Remark = tbCustomerRemark.Text;
            customer.Contacts = tbContacts.Text;
            customer.Phone = tbPhone.Text;
            if (tbNo.Text.Equals(string.Empty))
            {
                customer.No = null;
            }
            else
            {
                customer.No = zDataConverter.ToInt(tbNo.Text);
            }
            customer.Account = tbAccount.Text;
            customer.Address = tbAddress.Text;
            bllCustomer.Update(customer);

            head.CustomerAccount = customer.Account;
            head.CustomerAddress = customer.Address;
            head.CustomerContacts = customer.Contacts;
            head.CustomerNo = customer.No;
            head.CustomerPhone = customer.Phone;
            head.CustomerRemark = customer.Remark;

            head.Items.Clear();
            foreach (DataGridViewRow dgvr in xfDataGridView1.Rows)
            {
                if (!dgvr.IsNewRow)
                {
                    XF.Model.Bill_DTOItems item = new XF.Model.Bill_DTOItems();
                    item.Id = zDataConverter.ToInt(dgvr.Cells[ColId.Name].Value, -1);
                    item.OrderCode = head.OrderCode;
                    item.Item = dgvr.Index + 1;
                    item.MaterielName = zDataConverter.ToString(dgvr.Cells[ColMaterielName.Name].Value);
                    item.MaterielModel = zDataConverter.ToString(dgvr.Cells[ColMaterielModel.Name].Value);
                    XF.Model.Base_Materiel materiel = bllMateriel.GetModel(zDataConverter.ToString(dgvr.Cells[ColMaterielName.Name].Value), zDataConverter.ToString(dgvr.Cells[ColMaterielModel.Name].Value));
                    if (materiel == null)
                    {
                        materiel = new XF.Model.Base_Materiel();
                        materiel.MaterielName = zDataConverter.ToString(dgvr.Cells[ColMaterielName.Name].Value);
                        materiel.MaterielModel = zDataConverter.ToString(dgvr.Cells[ColMaterielModel.Name].Value);
                        item.MaterielId = bllMateriel.Add(materiel);
                    }
                    else
                    {
                        item.MaterielId = materiel.Id;
                    }
                    item.Unit = zDataConverter.ToInt(dgvr.Cells[ColUnit.Name].Value);
                    item.Qty = zDataConverter.ToDecimal(dgvr.Cells[ColDTOQty.Name].Value);
                    item.Price = zDataConverter.ToDecimal(dgvr.Cells[ColPrice.Name].Value);
                    item.STOItemId = zDataConverter.ToInt(dgvr.Cells[ColSTOItemId.Name].Value);
                    item.Remark = zDataConverter.ToString(dgvr.Cells[ColRemark.Name].Value);
                    head.Items.Add(item);
                }
            }
            //执行保存订单SQL
            if (bll.UpdateOrder(head) == (int)SqlEnum.Success)
            {
                QQMessageBox.Show(
                this,
                MessageText.TIP_SUCCESS_SAVE,
                MessageText.MESSAGEBOX_CAPTION_TIP,
                QQMessageBoxIcon.Information,
                QQMessageBoxButtons.OK);
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            else
            {
                QQMessageBox.Show(
                this,
                MessageText.TIP_ERROR_PLACE,
                MessageText.MESSAGEBOX_CAPTION_TIP,
                QQMessageBoxIcon.Error,
                QQMessageBoxButtons.OK);
            }
        }

        /// <summary>
        /// 数据校验
        /// </summary>
        /// <returns>校验结果信息，为空表示校验通过</returns>
        private string CheckInput()
        {
            if(zDataConverter.ToDecimal(tbPayAmount.Text,-999) == -999)
            {
                return MessageText.CHECK_ERROR_DTO_PAYAMOUNT;
            }
            if (!tbNo.Text.Equals(string.Empty))
            {
                if (zDataConverter.ToInt(tbNo.Text, -999) == -999)
                {
                    return MessageText.CHECK_ERROR_DTO_CUSTOMER_NO;
                }
                int payType = zDataConverter.ToInt(cmbPayType.SelectedValue);
                int no = zDataConverter.ToInt(tbNo.Text, -999);
                XF.Model.Base_Customer customer = bllCustomer.GetModel(payType, no);
                if (customer != null && customer.Id != iCustomerId)
                {
                    return MessageText.CHECK_REPEAT_CUSTOMER_NO;
                }
            }
            string msg = CheckItemInput();
            return msg;
        }

        /// <summary>
        /// 订单明细数据校验
        /// </summary>
        /// <returns>校验结果信息，为空表示校验通过</returns>
        private string CheckItemInput()
        {
            foreach (DataGridViewRow item in xfDataGridView1.Rows)
            {
                if (!item.IsNewRow)
                {
                    if (zDataConverter.ToInt(item.Cells[ColDTOQty.Name].Value, -999) == -999)
                    {
                        return MessageText.CHECK_ERROR_DTO_QTY;
                    }
                    else if (zDataConverter.ToDecimal(item.Cells[ColDTOQty.Name].Value, -999) == -999)
                    {
                        return MessageText.CHECK_ERROR_DTO_PRICE;
                    }
                }
            }
            return string.Empty;
        }

        private void FrmCustomerCard_Load(object sender, EventArgs e)
        {
            ColUnit.DisplayMember = MessageText.LISTITEM_TEXT;
            ColUnit.ValueMember = MessageText.LISTITEM_VALUE;
            ColUnit.DataSource = GenerateData.GetUnit(false);

            cmbPayType.DisplayMember = MessageText.LISTITEM_TEXT;
            cmbPayType.ValueMember = MessageText.LISTITEM_VALUE;
            cmbPayType.DataSource = GenerateData.GetPayType(false);

            cmbStatus.DisplayMember = MessageText.LISTITEM_TEXT;
            cmbStatus.ValueMember = MessageText.LISTITEM_VALUE;
            cmbStatus.DataSource = GenerateData.GetDTOStatus(false);

            InitData();
        }

        private void InitData()
        {
            List<XF.Model.Bill_DTOItems> items = bllItems.DataTableToList(bllItems.GetDetailList("OrderCode = '" + head.OrderCode + "'").Tables[0]);
            tbOrderCode.Text = head.OrderCode;
            dtpOrderDate.Value = (DateTime)head.OrderDate;
            tbOrderRemark.Text = head.Remark;
            iCustomerId = (int)head.CustomerId;
            tbCode.Text = head.CustomerCode;
            tbName.Text = head.CustomerName;
            cmbPayType.SelectedValue = zDataConverter.ToInt(head.PayType);
            cmbStatus.SelectedValue = zDataConverter.ToInt(head.Status);
            tbPayAmount.Text = zDataConverter.ToString(head.PayAmount);
            tbCustomerRemark.Text = head.CustomerRemark;
            tbContacts.Text = head.CustomerContacts;
            tbPhone.Text = head.CustomerPhone;
            tbNo.Text = head.CustomerNo == null ? string.Empty : zDataConverter.ToString(head.CustomerNo);
            tbAccount.Text = head.CustomerAccount;
            tbAddress.Text = head.CustomerAddress;
            int index = 0;
            foreach (XF.Model.Bill_DTOItems item in items)
            {
                xfDataGridView1.Rows.Add();
                xfDataGridView1.Rows[index].Cells[ColId.Name].Value = item.Id;
                xfDataGridView1.Rows[index].Cells[ColSTOItemId.Name].Value = item.STOItemId;
                xfDataGridView1.Rows[index].Cells[ColMaterielId.Name].Value = item.MaterielId;
                xfDataGridView1.Rows[index].Cells[ColMaterielName.Name].Value = item.MaterielName;
                xfDataGridView1.Rows[index].Cells[ColMaterielModel.Name].Value = item.MaterielModel;
                xfDataGridView1.Rows[index].Cells[ColUnit.Name].Value = zDataConverter.ToInt(item.Unit);
                xfDataGridView1.Rows[index].Cells[ColDTOQty.Name].Value = item.Qty;
                xfDataGridView1.Rows[index].Cells[ColPrice.Name].Value = item.Price;
                xfDataGridView1.Rows[index].Cells[ColTotle.Name].Value = item.Qty * item.Price;
                xfDataGridView1.Rows[index].Cells[ColRemark.Name].Value = item.Remark;
                index++;
            }

            if(head.Status != 0)
            {
                tsBtnDelete.Visible = false;
                xfDataGridView1.AllowUserToAddRows = false;
            }
            else
            {
                tsBtnDelete.Visible = true;
                xfDataGridView1.AllowUserToAddRows = true;
            }
        }

        private void tsBtnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void xfDataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                if (e.ColumnIndex == ColMaterielName.Index || e.ColumnIndex == ColMaterielModel.Index)
                {
                    FrmDialogDTOList frmDialogDTOList = new FrmDialogDTOList(iCustomerId);
                    frmDialogDTOList.Item.MaterielName = zDataConverter.ToString(xfDataGridView1.Rows[e.RowIndex].Cells[ColMaterielName.Name].Value);
                    frmDialogDTOList.Item.MaterielModel = zDataConverter.ToString(xfDataGridView1.Rows[e.RowIndex].Cells[ColMaterielModel.Name].Value);
                    frmDialogDTOList.Item.Qty = zDataConverter.ToDecimal(xfDataGridView1.Rows[e.RowIndex].Cells[ColDTOQty.Name].Value);
                    frmDialogDTOList.Item.Unit = zDataConverter.ToInt(xfDataGridView1.Rows[e.RowIndex].Cells[ColUnit.Name].Value);
                    frmDialogDTOList.Item.Price = zDataConverter.ToDecimal(xfDataGridView1.Rows[e.RowIndex].Cells[ColPrice.Name].Value);
                    frmDialogDTOList.Item.Remark = zDataConverter.ToString(xfDataGridView1.Rows[e.RowIndex].Cells[ColRemark.Name].Value);
                    if (frmDialogDTOList.ShowDialog() == DialogResult.OK)
                    {
                        if (xfDataGridView1.Rows[e.RowIndex].IsNewRow)
                        {
                            xfDataGridView1.Rows.Add();
                        }
                        xfDataGridView1.Rows[e.RowIndex].Cells[ColMaterielName.Name].Value = frmDialogDTOList.Item.MaterielName;
                        xfDataGridView1.Rows[e.RowIndex].Cells[ColMaterielModel.Name].Value = frmDialogDTOList.Item.MaterielModel;
                        xfDataGridView1.Rows[e.RowIndex].Cells[ColDTOQty.Name].Value = frmDialogDTOList.Item.Qty;
                        xfDataGridView1.Rows[e.RowIndex].Cells[ColUnit.Name].Value = frmDialogDTOList.Item.Unit;
                        xfDataGridView1.Rows[e.RowIndex].Cells[ColPrice.Name].Value = frmDialogDTOList.Item.Price;
                        xfDataGridView1.Rows[e.RowIndex].Cells[ColTotle.Name].Value = frmDialogDTOList.Item.Qty * frmDialogDTOList.Item.Price;
                        xfDataGridView1.Rows[e.RowIndex].Cells[ColRemark.Name].Value = frmDialogDTOList.Item.Remark;
                    }
                }
            }
        }

        private void xfDataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                if (e.ColumnIndex == ColPrice.Index || e.ColumnIndex == ColDTOQty.Index)
                {
                    decimal price = zDataConverter.ToDecimal(xfDataGridView1.Rows[e.RowIndex].Cells[ColPrice.Name].Value, 0);
                    decimal qty = zDataConverter.ToDecimal(xfDataGridView1.Rows[e.RowIndex].Cells[ColDTOQty.Name].Value, 0);
                    if (qty == 0)
                    {
                        xfDataGridView1.Rows[e.RowIndex].Cells[ColTotle.Name].Value = 0;
                    }
                    else
                    {
                        xfDataGridView1.Rows[e.RowIndex].Cells[ColTotle.Name].Value = price * qty;
                    }
                }
                else if (e.ColumnIndex == ColTotle.Index || e.ColumnIndex == ColDTOQty.Index)
                {
                    decimal totle = zDataConverter.ToDecimal(xfDataGridView1.Rows[e.RowIndex].Cells[ColTotle.Name].Value, 0);
                    decimal qty = zDataConverter.ToDecimal(xfDataGridView1.Rows[e.RowIndex].Cells[ColDTOQty.Name].Value, 0);
                    if (qty == 0)
                    {
                        xfDataGridView1.Rows[e.RowIndex].Cells[ColPrice.Name].Value = 0;
                    }
                    else
                    {
                        xfDataGridView1.Rows[e.RowIndex].Cells[ColPrice.Name].Value = totle / qty;
                    }
                }
            }
        }

        private void xfDataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
        {
            if (xfDataGridView1.IsCurrentCellDirty)
            {
                xfDataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
            }
        }

        private void FrmDTODetail_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.Enter:
                    tsBtnSave_Click(this, EventArgs.Empty);
                    break;
                case Keys.Escape:
                    tsBtnCancel_Click(this, EventArgs.Empty);
                    break;
            }
        }

        private void tsBtnDelete_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow dgvr in xfDataGridView1.SelectedRows)
            {
                xfDataGridView1.Rows.Remove(dgvr);
            }
        }
    }
}
